package com.shouhuobao.home;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.menu.WebViewActivity;
import com.collectplus.express.model.CalculatePriceBean;
import com.collectplus.express.model.CalculateProvinceBean;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.SameCityHistoryBean;
import com.collectplus.express.model.SameCityPriceBean;
import com.collectplus.express.self.SelfFormInfoActivity;
import com.collectplus.express.tools.TextWatcherExt;
import com.shouhuobao.bhi.loc.BaiduLocationService;
import com.shouhuobao.bhi.login.LoginActivity;
import com.shouhuobao.samecity.SameCityAddressActivity;
import com.shouhuobao.samecity.SameCityFormActivity;
import com.shouhuobao.samecity.SameCityReceiverAddressActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.ArrayList;

import droid.frame.ui.utils.Utils;
import droid.frame.utils.android.MathUtils;
import droid.frame.utils.lang.JsonParser;

/**
 * Created by joker on 2018/5/17.
 */
public class CalculatePriceActivity extends BaseActivity2 implements View.OnClickListener {

    private static final int NORMAL_TYPE = 1;//普通上门寄件类型
    private static final int SAMECITY_TYPE = 2;//同城寄件类型

    private String onlinePriceStr = "<font color=#404040>在线预计需支付</font><font color=#F5A623>{0}</font><font color=#404040>元</font>";
    private int nomarlWeight = 3;
    private int sameCityWeight = 5;
    private int currentType = 1;//记录当前展示类型，默认为上门普通寄件
    ArrayList<CalculateProvinceBean> provinceItems = new ArrayList<>();
    ArrayList<ArrayList<String>> cityItems = new ArrayList<>();

    private TextView mCalculateTypeTV;//根据切换类型展示相应的标题
    private TextView mCalculateTurnTV;//切换计算类型的按钮
    private TextView mWeightTV;//重量展示
    private TextView mSendAddressTV;//寄件人的位置
    private TextView mReceiveAddressTV;//收件人的位置
    private TextView mStampPriceTV;//邮票的价格
    private TextView mOnLinePriceTV;//在线需要支付的价格
    private TextView mPriceTipsTV;//支付价格提示

    private double latitude = 0;//寄件人的经纬度
    private double longitude = 0;
    private double targetLatitude = 0;//收件人的经纬度
    private double targetLongitude = 0;
    private CalculatePriceBean mPriceBean = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        location();
    }

    private void location() {
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getContext(), BaiduLocationService.class);
        intent.setPackage(getPackageName());
        intent.putExtra("msgId", MsgID.self_baidu_location);
        startService(intent);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_calculate_price);
        super.findViewById();
        getAppTitle().setCommonTitle("运费计算");
        mCalculateTypeTV = findViewById(R.id.calculate_type_tv);
        mCalculateTurnTV = findViewById(R.id.calculate_turn_tv);
        mCalculateTurnTV.setOnClickListener(this);
        findViewById(R.id.reduce_iv).setOnClickListener(this);
        findViewById(R.id.add_iv).setOnClickListener(this);
        mWeightTV = findViewById(R.id.weight_tv);
        mSendAddressTV = findViewById(R.id.send_address_tv);
        mSendAddressTV.setOnClickListener(this);
        mReceiveAddressTV = findViewById(R.id.receive_address_tv);
        mReceiveAddressTV.setOnClickListener(this);
        findViewById(R.id.subimt_order_bt).setOnClickListener(this);
        mSendAddressTV.addTextChangedListener(textWatcher);
        mReceiveAddressTV.addTextChangedListener(textWatcher);
        mStampPriceTV = findViewById(R.id.stamp_price_tv);
        mOnLinePriceTV = findViewById(R.id.online_price_tv);
        mPriceTipsTV = findViewById(R.id.price_tip_tv);
        mPriceTipsTV.setOnClickListener(this);
        findViewById(R.id.click_price_tip_tv).setOnClickListener(this);
        updateView();
        initData();
    }

    /**
     * 根据类型展示对应的视图
     */
    private void updateView() {
        //普通寄件视图
        if (currentType == NORMAL_TYPE) {
            mCalculateTypeTV.setText("寄件费用计算器");
            mCalculateTurnTV.setText("切换为同城直送计算器");
            Drawable drawableRight = getResources().getDrawable(R.drawable.white_down_icon);
            mSendAddressTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
            mSendAddressTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
            mReceiveAddressTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
            mReceiveAddressTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
            mWeightTV.setText(nomarlWeight + "");
        } else {
            mCalculateTypeTV.setText("同城直送计算器");
            mCalculateTurnTV.setText("切换为寄件费用计算器");
            Drawable drawableRight = getResources().getDrawable(R.drawable.samecity_white_right_icon);
            mSendAddressTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
            mSendAddressTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
            mReceiveAddressTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
            mReceiveAddressTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
            mWeightTV.setText(sameCityWeight + "");
        }
        mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, 0.00)));
    }

    private void initData() {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = getContext().getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open("province.json")));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        provinceItems = JsonParser.parseList(stringBuilder.toString(), CalculateProvinceBean.class);
        for (int i = 0; i < provinceItems.size(); i++) {
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            for (int j = 0; j < provinceItems.get(i).getCityList().size(); j++) {
                cityList.add(provinceItems.get(i).getCityList().get(j).getName());
            }
            cityItems.add(cityList);
        }
    }

    private TextWatcherExt textWatcher = new TextWatcherExt() {
        public void afterTextChanged(Editable s) {
            if (mSendAddressTV.getTag() != null
                    && mReceiveAddressTV.getTag() != null && latitude > 0 && longitude > 0) {
                if (currentType == SAMECITY_TYPE) {
                    if (targetLatitude > 0 && targetLongitude > 0) {
                        initPrice();
                    }
                } else {
                    initPrice();
                }
            }
        }

    };

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //点击查看邮票的
            case R.id.price_tip_tv:
                intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "邮票使用介绍");
                startActivity(intent);
                break;
            //点击查看计价规则
            case R.id.click_price_tip_tv:
                intent = new Intent();
                intent.setClass(getContext(), WebViewActivity.class);
                if (currentType == NORMAL_TYPE) {
                    intent.putExtra("title", "价格说明");
                } else {
                    intent.putExtra("title", "计价规则");
                }
                startActivity(intent);
                break;
            //切换计算器的按钮
            case R.id.calculate_turn_tv:
                //如果是普通寄件，则切换为同城寄件
                if (currentType == NORMAL_TYPE) {
                    currentType = SAMECITY_TYPE;
                    sameCityWeight = 5;
                } else {
                    currentType = NORMAL_TYPE;
                    nomarlWeight = 3;
                }
                mSendAddressTV.setTag(null);
                mSendAddressTV.setText(null);
                mReceiveAddressTV.setTag(null);
                mReceiveAddressTV.setText("请选择");
                location();
                break;
            //重量进行相减
            case R.id.reduce_iv:
                if (mSendAddressTV.getTag() == null || mReceiveAddressTV.getTag() == null) {
                    showToast("请选择需要计算的寄件或收件地址");
                    return;
                }
                //普通寄件
                if (currentType == NORMAL_TYPE) {
                    if (nomarlWeight <= 1) {
                        nomarlWeight = 1;
                    } else {
                        nomarlWeight--;
                    }
                    mWeightTV.setText(nomarlWeight + "");
                    calculateNormalSendPrice();
                } else {
                    if (sameCityWeight <= 1) {
                        sameCityWeight = 1;
                    } else {
                        sameCityWeight--;
                    }
                    mWeightTV.setText(sameCityWeight + "");
                    calculateSameCityPrice();
                }
                break;
            //重量进行相加
            case R.id.add_iv:
                if (mSendAddressTV.getTag() == null || mReceiveAddressTV.getTag() == null) {
                    showToast("请选择需要计算的寄件或收件地址");
                    return;
                }
                //普通寄件
                if (currentType == NORMAL_TYPE) {
                    if (nomarlWeight >= 99) {
                        nomarlWeight = 99;
                    } else {
                        nomarlWeight++;
                    }
                    mWeightTV.setText(nomarlWeight + "");
                    calculateNormalSendPrice();
                } else {
                    if (sameCityWeight >= 99) {
                        sameCityWeight = 99;
                    } else {
                        sameCityWeight++;
                    }
                    mWeightTV.setText(sameCityWeight + "");
                    calculateSameCityPrice();
                }
                break;
            //立即下单
            case R.id.subimt_order_bt:
                //普通寄件
                if (currentType == NORMAL_TYPE) {
                    startActivity(SelfFormInfoActivity.class);
                } else {
                    startActivity(SameCityFormActivity.class);
                }
                finish();
                break;
            //点击选择寄件人地址,如果是普通寄件，寄件人选择省市
            case R.id.send_address_tv:
                //普通寄件
                if (currentType == NORMAL_TYPE) {
                    selectProvince(true);
                }
                //同城寄件
                else {
                    intent = new Intent(getContext(), SameCityAddressActivity.class);
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 1701);
                }
                break;
            //点击选择收件人地址，如果是普通寄件，收件人显示省
            case R.id.receive_address_tv:
                if (currentType == NORMAL_TYPE) {
                    selectProvince(false);
                } else {
                    intent = new Intent();
                    if (AppCache.isLogin() == false) {
                        intent.setClass(getContext(), LoginActivity.class);
                    } else {
                        intent.setClass(getContext(), SameCityReceiverAddressActivity.class);
                    }
                    intent.putExtra("type", 1);
                    startActivityForResult(intent, 1702);
                }
                break;
        }
    }

    /*********************************************************************普通寄件逻辑视图处理***************************************************************/
    /**
     * 选择省市
     */
    private void selectProvince(boolean isShowCity) {
        if (isShowCity) {
            DialogMgr.calculateSelectProvincePopWin(getContext(), findViewById(R.id.subimt_order_bt), provinceItems, cityItems, null);
        } else {
            DialogMgr.calculateSelectProvincePopWin(getContext(), findViewById(R.id.subimt_order_bt), provinceItems, null, null);
        }
    }

    /**
     * 设置寄件人地址或收件人地址
     *
     * @param type 1 寄件人的地址，显示市   2 收件人的地址，显示省
     */
    public void setAddressData(int type, String province, String city) {
        if (type == 1) {
            mSendAddressTV.setTag(city);
            mSendAddressTV.setText(city);
        } else {
            mReceiveAddressTV.setTag(province);
            mReceiveAddressTV.setText(province);
        }
    }

    /**
     * 初始化计算价格
     */
    private void initPrice() {
        showLoadingDialog(null);
        if (currentType == NORMAL_TYPE) {
            AppHttp.getInstance().initCalculatePrice(longitude, latitude, sameCityWeight, Const.ParcelType.visitToHome, mSendAddressTV.getText().toString(), mReceiveAddressTV.getText().toString(), targetLongitude, targetLatitude);
        } else {
            AppHttp.getInstance().initCalculatePrice(longitude, latitude, sameCityWeight, Const.ParcelType.sameCityToHome, AppCache.getCurrentCityName(), mReceiveAddressTV.getText().toString(), targetLongitude, targetLatitude);
        }
    }

    /**
     * 计算普通价格
     */
    private void calculateNormalSendPrice() {
        if (mPriceBean == null) {
            mStampPriceTV.setText("0");
            mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, 0.00)));
            return;
        }
        if (nomarlWeight == 1) {
            //说明有一公斤的邮票
            if (mPriceBean.getCoupon1() > 0) {
                mPriceTipsTV.setText("使用火箭邮票支付");
                Drawable drawableRight = getResources().getDrawable(R.drawable.self_receiver_help_icon);
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                mPriceTipsTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                mPriceTipsTV.setOnClickListener(this);
                mOnLinePriceTV.setVisibility(View.VISIBLE);
                mStampPriceTV.setText(mPriceBean.getCoupon1() + "");
                mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, mPriceBean.getSimplePrice())));
            } else {
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mPriceTipsTV.setOnClickListener(null);
                mOnLinePriceTV.setVisibility(View.GONE);
                mPriceTipsTV.setText("在线预计需支付");
                mStampPriceTV.setText(mPriceBean.getSimplePrice() + "");
            }
        } else if (nomarlWeight > 1 && nomarlWeight <= 3) {
            //说明有3公斤的邮票
            if (mPriceBean.getCoupon3() > 0) {
                Drawable drawableRight = getResources().getDrawable(R.drawable.self_receiver_help_icon);
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                mPriceTipsTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                mPriceTipsTV.setOnClickListener(this);
                mPriceTipsTV.setText("使用火箭邮票支付");
                mOnLinePriceTV.setVisibility(View.VISIBLE);
                mStampPriceTV.setText(mPriceBean.getCoupon3() + "");
                mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, mPriceBean.getSimplePrice())));
            } else {
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mPriceTipsTV.setOnClickListener(null);
                mOnLinePriceTV.setVisibility(View.GONE);
                mPriceTipsTV.setText("在线预计需支付");
                mStampPriceTV.setText(mPriceBean.getSimplePrice() + "");
            }
        } else {
            mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            mPriceTipsTV.setOnClickListener(null);
            mOnLinePriceTV.setVisibility(View.GONE);
            mPriceTipsTV.setText("在线预计需支付");
            double price = MathUtils.add(mPriceBean.getSimplePrice(), MathUtils.mul(nomarlWeight - 3, mPriceBean.getFlowPrice()));
            mStampPriceTV.setText(price + "");
        }
    }

    /************************************************************同城的相关处理************************************************************************************************************/
    /**
     * 计算同城价格
     */
    private void calculateSameCityPrice() {
        if (mPriceBean == null) {
            mStampPriceTV.setText("0");
            mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, 0.00)));
        }
        SameCityPriceBean cityPriceBean = mPriceBean.getCgp();
        if (sameCityWeight <= 5) {
            //说明有5公斤的邮票
            if (mPriceBean.getCoupon5() > 0) {
                Drawable drawableRight = getResources().getDrawable(R.drawable.self_receiver_help_icon);
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null);
                mPriceTipsTV.setCompoundDrawablePadding(Utils.dpToPx(5, getResources()));
                mPriceTipsTV.setOnClickListener(this);
                mPriceTipsTV.setText("使用火箭邮票支付");
                mOnLinePriceTV.setVisibility(View.VISIBLE);
                mStampPriceTV.setText(mPriceBean.getCoupon5() + "");
                if (cityPriceBean != null) {
                    if (mPriceBean.getDistanceTotal() > cityPriceBean.getStartDistance()) {
                        mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, MathUtils.add(cityPriceBean.getStartPrice(), MathUtils.mul(Math.ceil(MathUtils.sub(mPriceBean.getDistanceTotal(), cityPriceBean.getStartDistance())), cityPriceBean.getContinueDistance())))));
                    } else {
                        mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, mPriceBean.getCost())));
                    }
                } else {
                    mOnLinePriceTV.setText(Html.fromHtml(MessageFormat.format(onlinePriceStr, mPriceBean.getCost())));
                }
            } else {
                mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
                mPriceTipsTV.setOnClickListener(null);
                mOnLinePriceTV.setVisibility(View.GONE);
                mPriceTipsTV.setText("在线预计需支付");
                mStampPriceTV.setText(mPriceBean.getCost() + "");
            }
        } else {
            mPriceTipsTV.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            mPriceTipsTV.setOnClickListener(null);
            mOnLinePriceTV.setVisibility(View.GONE);
            mPriceTipsTV.setText("在线预计需支付");
            if (cityPriceBean != null) {
                double distancePrice = 0;
                double weightPrice = 0;
                if (mPriceBean.getDistanceTotal() > cityPriceBean.getStartDistance()) {
                    distancePrice = MathUtils.mul(Math.ceil(MathUtils.sub(mPriceBean.getDistanceTotal(), cityPriceBean.getStartDistance())), cityPriceBean.getContinueDistance());
                }
                if (sameCityWeight > cityPriceBean.getStartWeight()) {
                    weightPrice = MathUtils.mul(Math.ceil(MathUtils.sub(sameCityWeight, cityPriceBean.getStartWeight())), cityPriceBean.getContinueWeight());
                }
                double price = MathUtils.add(MathUtils.add(cityPriceBean.getStartPrice(), distancePrice), weightPrice);
                mStampPriceTV.setText(price + "");
            } else {
                mStampPriceTV.setText(mPriceBean.getCost() + "");
            }
        }
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            //定位饭回来的
            case MsgID.self_baidu_location:
                cancelLoadingDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        BDLocation location = (BDLocation) msg.obj;
                        if (location != null && isNotEmpty(location.getCity())) {
                            //如果是普通寄件，则寄件人为当前的省
                            if (currentType == NORMAL_TYPE) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                                mSendAddressTV.setTag(location.getCity());
                                mSendAddressTV.setText(location.getCity());
                            } else {
                                targetLatitude = location.getLatitude();
                                targetLongitude = location.getLongitude();
                                if (location.getPoiList() != null && location.getPoiList().size() > 0) {
                                    mSendAddressTV.setTag(location.getPoiList().get(0).getName());
                                    mSendAddressTV.setText(location.getPoiList().get(0).getName());
                                } else {
                                    mSendAddressTV.setTag(null);
                                    mSendAddressTV.setText("请选择");
                                }
                            }
                        } else {
                            showToast("定位失败");
                        }
                        updateView();
                    }
                });
                return false;
            //初始化计算价格返回的数据
            case MsgID.init_calculate_price:
                cancelLoadingDialog();
                final AppResult<CalculatePriceBean> appResult = JSON.parser(msg.obj, CalculatePriceBean.class);
                if (appResult.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPriceBean = appResult.getResult();
                            if (currentType == NORMAL_TYPE) {
                                calculateNormalSendPrice();
                            } else {
                                calculateSameCityPrice();
                            }
                        }
                    });
                } else {
                    showToast(appResult.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (1701 == requestCode) {
            SameCityHistoryBean cityHistoryBean = (SameCityHistoryBean) data.getSerializableExtra("item");
            if (cityHistoryBean != null) {
                latitude = cityHistoryBean.getLatitude();
                longitude = cityHistoryBean.getLongitude();
                mSendAddressTV.setTag(cityHistoryBean.getBuildName());
                mSendAddressTV.setText(cityHistoryBean.getBuildName());
            }
        } else if (1702 == requestCode) {
            SameCityHistoryBean cityHistoryBean = (SameCityHistoryBean) data.getSerializableExtra("item");
            if (cityHistoryBean != null) {
                targetLatitude = cityHistoryBean.getLatitude();
                targetLongitude = cityHistoryBean.getLongitude();
                mReceiveAddressTV.setTag(cityHistoryBean.getBuildName());
                mReceiveAddressTV.setText(cityHistoryBean.getBuildName());
            }
        }
    }
}
